package com.jbwz.web.cms.controller;


import com.jbwz.web.cms.common.ResponseCodeCMS;
import com.jbwz.web.cms.entity.GoodsCategory;
import com.jbwz.web.cms.entity.GoodsCr;
import com.jbwz.web.cms.entity.vo.GoodsCategoryVO;
import com.jbwz.web.cms.service.GoodsCategoryService;
import com.jbwz.web.cms.service.GoodsCrService;
import com.jbwz.web.common.base.BaseController;
import com.jbwz.web.common.exception.BusinessException;
import com.jbwz.web.common.res.ResponseJson;
import com.jbwz.web.common.validated.InsertGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yyh
 * @since 2022-02-03 09:32:08
 */
@RestController
@RequestMapping("/goods-category")
public class GoodsCategoryController extends BaseController {

    @Autowired
    GoodsCategoryService goodsCategoryService;
    @Autowired
    GoodsCrService goodsCrService;

    @GetMapping("/list")
    public ResponseJson list(@Validated GoodsCategoryVO vo) {
        List<GoodsCategory> result = goodsCategoryService.listFind(vo);
        return success(result);
    }

    @PostMapping("/save")
    public ResponseJson save(@RequestBody @Validated(InsertGroup.class) GoodsCategoryVO vo) {
        goodsCategoryService.saveOrUpdateVO(vo);
        return success();
    }

    @PostMapping("/sort-up")
    public ResponseJson sortUpdate(@RequestBody @Validated List<GoodsCategoryVO> vos) {
        goodsCategoryService.updateSorted(vos);
        return success();
    }

    @GetMapping("/status")
    public ResponseJson statusUpdate(GoodsCategoryVO vo) {
        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setStatus(vo.getStatus());
        goodsCategory.setId(vo.getId());
        goodsCategoryService.updateById(goodsCategory);
        return success();
    }

    @GetMapping("/del/{id}")
    public ResponseJson del(@PathVariable("id") Long id) {
        List<GoodsCr> gcrList = goodsCrService.findByCategoryId(id);
        if (CollectionUtils.isEmpty(gcrList)) {
            goodsCategoryService.removeById(id);
        } else {
            throw BusinessException.resMsg(ResponseCodeCMS.HAS_RELATION_SHIP.withMsg("有关联的菜品,不能删除"));
        }
        return success();
    }

    @GetMapping("/detail/{id}")
    public ResponseJson detail(@PathVariable("id") Long id) {
        GoodsCategory e = goodsCategoryService.getById(id);
        return success(goodsCategoryService.toVO(e));
    }

}
